import { appRoutes } from './router'
import { done, start } from '@/utils/nprogress'
import {
  createRouter,
  createWebHashHistory,
  type RouteRecordRaw
} from 'vue-router'
import { Title } from '@/config'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    meta: { title: '登录' },
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/403',
    name: '403',
    meta: { title: '403' },
    component: () => import('@/views/403/index.vue')
  },
  {
    path: '/404',
    name: '404',
    meta: { title: '404' },
    component: () => import('@/views/404/index.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
appRoutes.forEach((route) => {
  router.addRoute(route)
})
router.beforeEach((to, from, next) => {
  start()
  // const isLogin = sessionStorage.getItem('cloud-token')
  // to.query.redirect = String(from.name || "");
  // if (to.name !== 'Login' && !isLogin) {
  //   next({ name: 'Login' })
  // } else if (to.name === 'Login' && isLogin) {
  //   next(false)
  // } else if (to.name === '404' || to.name === '403') {
  //   next()
  // } else {
  //   const { permission } = to.meta
  //   if (permission) {
  //     const sessionPer = sessionStorage.getItem('cloud-permissions')
  //     let curPermissions: string[] = []
  //     if (sessionPer) {
  //       curPermissions = JSON.parse(sessionPer)
  //       if (curPermissions.some((p) => p === permission)) {
  //         return next()
  //       }
  //     }
  //     next({ name: '403' })
  //   } else {
  //     next()
  //   }
  // }
  next()
})

router.afterEach((guard) => {
  if (guard.meta.title) {
    document.title = `${guard.meta.title} - ${Title}`
  }

  done()
})
// export default router
export { router as default, appRoutes }
